package com.junzhiit.nengji.api.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.junzhiit.nengji.api.service.CartService;
import com.junzhiit.nengji.api.web.exception.CartNotFoundException;
import com.junzhiit.nengji.api.web.exception.GoodsNotFoundException;
import com.junzhiit.nengji.api.web.exception.OutOfStockException;
import com.junzhiit.nengji.api.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.api.web.exception.SkuContentNotFoundException;
import com.junzhiit.nengji.api.web.exception.UserNotFoundException;
import com.junzhiit.nengji.api.web.vo.CartAddVO;
import com.junzhiit.nengji.api.web.vo.CartEditVO;
import com.junzhiit.nengji.api.web.vo.CartGoodsVO;
import com.junzhiit.nengji.api.web.vo.CartShopVO;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.api.web.vo.SkuContentVO;
import com.junzhiit.nengji.api.web.vo.SkuItemsVO;
import com.junzhiit.nengji.api.web.vo.SkuVO;
import com.junzhiit.nengji.bo.CartBO;
import com.junzhiit.nengji.bo.GoodsSkuItemsBO;
import com.junzhiit.nengji.dao.CartDAO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.GoodsSkuItemsDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.SkuContentDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.model.Cart;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.SkuContent;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.ShopIsPlatform;
import com.junzhiit.nengji.model.enums.Status;

@Service
public class CartServiceImpl extends BaseServiceImpl implements CartService {
	
	@Autowired
	private CartDAO cartDAO;
	
	@Autowired
	private ShopDAO shopDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private GoodsDAO goodsDAO;
	
	@Autowired
	private SkuContentDAO skuContentDAO;
	
	@Autowired
	private GoodsSkuItemsDAO goodsSkuItemsDAO;

	@Override
	public ResultVO add(CartAddVO cartAddVO) {
		ResultVO result =new ResultVO();
		
		Shop shop=shopDAO.query(cartAddVO.getShopId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		User user=userDAO.query(cartAddVO.getUserId());
		if (user == null) {
			throw new UserNotFoundException("用户不存在");
		}
		Goods goods=goodsDAO.query(cartAddVO.getGoodsId());
		if (goods == null) {
			throw new GoodsNotFoundException("商品不存在");
		}
		
		//获得库存
		//Integer stock=goods.getStock();
		
		if(StringUtils.isNotBlank(cartAddVO.getSkuContentId())){
			SkuContent skuContent=skuContentDAO.query(cartAddVO.getSkuContentId());
			if (skuContent == null) {
				throw new SkuContentNotFoundException("skuContent不存在");
			}
			//stock=skuContent.getStock();
		}
		
		Cart cart =new Cart();
		BeanUtils.copyProperties(cartAddVO, cart);
		
		//查找购物车同一商品
		Cart param= cartDAO.findCart(cart);
		
		if(param!=null && param.getStatus() != 1){
			Integer number =param.getNumber()+cart.getNumber();
		/*	if(number>stock){
				throw new OutOfStockException("购买数量超出库存");
			}*/
			
			param.setNumber(number);
			param.setUpdatedTime(new Date());
			
			cartDAO.update(param);
		}else{		
		/*	if(cartAddVO.getNumber()>stock){
				throw new OutOfStockException("购买数量超出库存");
			}*/
			
			cart.setStatus(Status.ACTIVE.toIntStatus());
			cartDAO.insert(cart);
		}
		
		Integer count=cartDAO.sumGoodsNumber(cartAddVO.getUserId(),null);
		result.setData(count);	
		
		return result;
	}

	@Override
	@Transactional
	public ResultVO edit(CartEditVO cartEditVO) {
		ResultVO result =new ResultVO();
		
		Cart cart=cartDAO.query(cartEditVO.getId());
		if (cart == null) {
			throw new CartNotFoundException("购物车不存在");
		}
		
		//获得商品库存
		Integer stock=0;
		String skuContentId=cart.getSkuContentId();
		Cart param=null;
		if(StringUtils.isNotBlank(skuContentId))
		{			
			if(StringUtils.isNotBlank(cartEditVO.getSkuContentId())){
				skuContentId=cartEditVO.getSkuContentId();
				
				Cart cartParam=new Cart();
				cartParam.setGoodsId(cart.getGoodsId());
				cartParam.setSkuContentId(skuContentId);
				cartParam.setUserId(cart.getUserId());
				param= cartDAO.findCart(cartParam);
			}
			
			SkuContent skuContent=skuContentDAO.query(skuContentId);
			if (skuContent == null) {
				throw new SkuContentNotFoundException("skuContent不存在");
			}
			stock=skuContent.getStock();
		}else{
			Goods goods=goodsDAO.query(cart.getGoodsId());
			stock=goods.getStock();
		}
		
		//获得商品购买数量
		Integer number=0;
		if(cartEditVO.getNumber()!=null){
			number=cartEditVO.getNumber();
		}else{
			number=cart.getNumber();
		}
		
		//判断是否存在购物车同一商品
		if(param!=null&&!param.getId().equals(cart.getId())){
			number+=param.getNumber();
		}
		
		if(number>stock){
			throw new OutOfStockException("购买数量超出库存");
		}
			
		BeanUtils.copyProperties(cartEditVO, cart);
		cart.setNumber(number);
		cart.setUpdatedTime(new Date());
		
		if(param!=null&&!param.getId().equals(cart.getId())){
			cartDAO.updateToDelete(param.getId());
		}
		
		result.setData(cartDAO.update(cart));
		return result;
	}

	@Override
	public ResultVO findAll(String userId) {
		ResultVO result =new ResultVO();
		User user=userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户不存在");
		}
		
		//查询购物车并组装购物车商品
		List<Shop> shopList=cartDAO.getCartShop(userId);
		List<CartBO> list=cartDAO.findAll(userId,null,ShopIsPlatform.HEADQUARTERS.toIntStatus(),Is.YES.toIntValue());
		
		List<CartShopVO> cartList=new ArrayList<CartShopVO>();
		List<CartGoodsVO> inactiveGoodsList =new ArrayList<CartGoodsVO>();
		for (Shop shop : shopList) {
			CartShopVO cartShopVO=new CartShopVO();
			cartShopVO.setShopId(shop.getId());
			cartShopVO.setShopName(shop.getName());
			cartShopVO.setIsShop(shop.getIsShop());
			cartShopVO.setIsMail(shop.getIsMail());
			cartShopVO.setIsReserve(shop.getIsReserve());
			cartShopVO.setIsEat(shop.getIsEat());
			cartShopVO.setIsDelivery(shop.getIsDelivery());
			
			cartShopVO.setShopHeadImgUrl(shop.getShopHeadImgUrl());
			List<CartGoodsVO> goodsList =new ArrayList<CartGoodsVO>();
			for (CartBO cartBO : list) {
				if(shop.getId().equals(cartBO.getShopId())){
					CartGoodsVO cartGoodsVO=new CartGoodsVO();
					BeanUtils.copyProperties(cartBO, cartGoodsVO);
					if(cartGoodsVO.getStatus()==Status.ACTIVE.toIntStatus()){
						goodsList.add(cartGoodsVO);
					}else if(cartGoodsVO.getStatus()==Status.INACTIVE.toIntStatus()){
						inactiveGoodsList.add(cartGoodsVO);
					}
				}
			}
			cartShopVO.setGoodsList(goodsList);
			if(goodsList.size()>0){
				cartList.add(cartShopVO);
			}
		}
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("cart", cartList);
		map.put("inactiveGoods", inactiveGoodsList);

		result.setData(map);
		return result;
	}

	@Override
	public ResultVO getGoodsSku(String goodsId) {
		ResultVO result =new ResultVO();
		Map<String, Object> map=new HashMap<String, Object>();
		Goods goods=goodsDAO.query(goodsId);
		if (goods == null) {
			throw new GoodsNotFoundException("商品不存在");
		}
		
		List<GoodsSkuItemsBO> goodsSkuItemsBOs=goodsSkuItemsDAO.queryGoodsSkuItemsBO(goodsId);
		
		Map<String, SkuVO> skuVOMap = new LinkedHashMap<String, SkuVO>();
		
		for (GoodsSkuItemsBO bo : goodsSkuItemsBOs) {
			SkuVO skuVO = skuVOMap.get(bo.getSkuId());
	        if (skuVO==null) {
	        	skuVO = new SkuVO();
	        	skuVO.setId(bo.getSkuId());
	        	skuVO.setName(bo.getName());
	        	skuVO.setIsOpenImage(bo.getIsOpenImage());
	        	List<SkuItemsVO> skuItemsList = new ArrayList<SkuItemsVO>();
	        	skuVO.setSkuItemsList(skuItemsList);
	        	skuVOMap.put(skuVO.getId(),skuVO);
	        }
	        
	        SkuItemsVO skuItemsVO=new SkuItemsVO();
	        skuItemsVO.setId(bo.getSkuItemsId());
	        skuItemsVO.setSkuId(bo.getSkuId());
	        skuItemsVO.setStandard(bo.getStandard());
	        skuItemsVO.setIsOpenImage(bo.getIsOpenImage());
	        skuItemsVO.setImage(bo.getImage());
	        skuVO.getSkuItemsList().add(skuItemsVO);
	    }
		Collection<SkuVO> data = skuVOMap.values();
		map.put("skuList", data);
		
		//查询skuContent
		List<SkuContent> SkuContentList= skuContentDAO.findSkuContentByGoodsId(goodsId);
		List<SkuContentVO> skuContentVOList= new ArrayList<SkuContentVO>();
		for (SkuContent skuContent : SkuContentList) {
			SkuContentVO skuContentVO=new SkuContentVO();
			skuContent.setStandards(skuContent.getStandards().replace("+", ";"));
			BeanUtils.copyProperties(skuContent, skuContentVO);		
			skuContentVOList.add(skuContentVO);
		}
		map.put("skuContentList", skuContentVOList);
		
		result.setData(map);
		return result;
	}

	@Override
	@Transactional
	public ResultVO batchDelCart(String[] ids) {
		ResultVO result = new ResultVO();
		if (ids.length <= 0) {
			return result;
		}
		result.setData(cartDAO.batchUpdateToDelete(ids));
		return result;
	}

	@Override
	public ResultVO sumGoodsNumber(String userId) {
		ResultVO result=new ResultVO();
		
		User user=userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户不存在");
		}
		
		result.setData(cartDAO.sumGoodsNumber(userId,null));
		return result;
	}
	
}
